// pages/menu/menu.js
const request = require('../utils/request')

Page({
    // 页面的初始数据
    data: {
        // 商品分类列表
        categories: [
            { id: 1, name: '全部', icon: '/assets/icons/all.png' },
            { id: 2, name: '外卖美食', icon: '/assets/icons/food.png' },
            { id: 3, name: '甜点饮品', icon: '/assets/icons/drink.png' },
            { id: 4, name: '夜宵', icon: '/assets/icons/night.png' },
            { id: 5, name: '超市便利', icon: '/assets/icons/market.png' },
            { id: 6, name: '品质百货', icon: '/assets/icons/shop.png' }
        ],
        currentCategory: 1, // 当前选中的分类ID
        currentCategoryName: '全部', // 当前选中的分类名称
        dishes: [], // 所有菜品列表
        filteredDishes: [], // 经过筛选后的菜品列表（根据分类和搜索关键词）
        totalPrice: 0, // 购物车总价
        selectedDishes: {}, // 已选菜品的数量映射表 {菜品id: 数量}
        selectedItems: [] // 购物车中的菜品列表
    },
    
    // 页面加载时执行
    onLoad() {
        // 从本地存储获取购物车数据并初始化已选菜品数量
        const cartItems = wx.getStorageSync('cartItems') || [];
        const selectedDishes = {};
        cartItems.forEach(item => {
            selectedDishes[item.id] = item.quantity;
        });
    
        // 设置数据并加载菜品列表
        this.setData({ selectedDishes }, () => {
            this.loadDishes();
        });
    },
    
    // 加载菜品列表数据
    async loadDishes() {
        try {
            const res = await request('/api/menu/dishes');
            if (res.data) {
                // 获取本地存储的已选菜品数量
                const selectedDishes = wx.getStorageSync('selectedDishes') || {};
                
                // 将菜品数据与已选数量合并
                const allDishes = res.data.map(dish => ({
                    ...dish,
                    quantity: selectedDishes[dish.id] || 0
                }));
                
                // 根据搜索关键词筛选菜品
                const filteredDishes = allDishes.filter(dish =>
                    !this.data.searchKeyword || dish.name.toLowerCase().includes(this.data.searchKeyword.toLowerCase())
                );
                
                // 更新页面数据
                this.setData({
                    dishes: allDishes,
                    filteredDishes,
                    selectedDishes,
                });
                
                // 计算购物车总数量
                const totalQuantity = Object.values(selectedDishes).reduce((sum, quantity) => sum + quantity, 0);
                
                this.setData({
                    cartCount: totalQuantity
                });
            }
        } catch (error) {
            console.error('获取菜品列表失败:', error);
            wx.showToast({
                title: '获取菜品列表失败',
                icon: 'none'
            });
        }
    },
    
    // 切换商品分类
    switchCategory(e) {
        const id = e.currentTarget.dataset.id;
        const category = this.data.categories.find(item => item.id === id);
        const { dishes, selectedDishes } = this.data;
    
        // 根据分类ID筛选菜品，同时保持已选数量
        const filteredDishes = dishes.filter(dish => 
            id === 1 || dish.category_id === id
        ).map(dish => ({
            ...dish,
            quantity: selectedDishes[dish.id] || 0
        }));
    
        // 更新当前分类和筛选后的菜品列表
        this.setData({
            currentCategory: id,
            currentCategoryName: category.name,
            filteredDishes
        });
    },
    
    // 计算购物车总价
    calculateTotal() {
        const { selectedDishes, dishes } = this.data;
        return dishes.reduce((total, dish) => {
            const quantity = selectedDishes[dish.id] || 0;
            return total + (dish.price * quantity);
        }, 0).toFixed(2);
    },

    // 增加菜品数量
    increaseQuantity(e) {
        const { id } = e.currentTarget.dataset;
        const { selectedDishes, filteredDishes, dishes } = this.data;
    
        // 更新选中菜品数量
        const updatedSelectedDishes = { ...selectedDishes };
        updatedSelectedDishes[id] = (updatedSelectedDishes[id] || 0) + 1;
    
        // 更新筛选后的菜品列表中的数量
        const updatedFilteredDishes = filteredDishes.map(dish => ({
            ...dish,
            quantity: dish.id === id ? updatedSelectedDishes[dish.id] : (selectedDishes[dish.id] || 0)
        }));
    
        // 更新所有菜品列表中的数量
        const updatedDishes = dishes.map(dish => ({
            ...dish,
            quantity: dish.id === id ? updatedSelectedDishes[dish.id] : (selectedDishes[dish.id] || 0)
        }));
    
        // 更新购物车中的菜品列表
        const selectedItems = updatedDishes
            .filter(dish => updatedSelectedDishes[dish.id] > 0)
            .map(dish => ({
                id: dish.id,
                name: dish.name,
                price: dish.price,
                image: dish.image,
                category_id: dish.category_id,
                quantity: updatedSelectedDishes[dish.id]
            }));
    
        // 计算新的总价
        const newTotal = selectedItems.reduce((total, item) => {
            return total + (item.price * item.quantity);
        }, 0).toFixed(2);
    
        // 更新页面数据
        this.setData({
            selectedDishes: updatedSelectedDishes,
            filteredDishes: updatedFilteredDishes,
            dishes: updatedDishes,
            selectedItems,
            totalPrice: newTotal
        });
    
        // 更新本地存储
        this.updateCartStorage();
    },

    // 减少菜品数量
    decreaseQuantity(e) {
        const { id } = e.currentTarget.dataset;
        const { selectedDishes, filteredDishes, dishes } = this.data;
    
        // 检查当前数量
        const currentQuantity = selectedDishes[id] || 0;
        if (currentQuantity <= 0) return;
    
        // 更新选中菜品数量
        const updatedSelectedDishes = { ...selectedDishes };
        updatedSelectedDishes[id] = currentQuantity - 1;
    
        // 更新筛选后的菜品列表中的数量
        const updatedFilteredDishes = filteredDishes.map(dish => ({
            ...dish,
            quantity: dish.id === id ? updatedSelectedDishes[dish.id] : (selectedDishes[dish.id] || 0)
        }));
    
        // 更新所有菜品列表中的数量
        const updatedDishes = dishes.map(dish => ({
            ...dish,
            quantity: dish.id === id ? updatedSelectedDishes[dish.id] : (selectedDishes[dish.id] || 0)
        }));
    
        // 更新购物车中的菜品列表
        const selectedItems = updatedDishes
            .filter(dish => updatedSelectedDishes[dish.id] > 0)
            .map(dish => ({
                id: dish.id,
                name: dish.name,
                price: dish.price,
                image: dish.image,
                category_id: dish.category_id,
                quantity: updatedSelectedDishes[dish.id]
            }));
    
        // 计算新的总价
        const newTotal = selectedItems.reduce((total, item) => {
            return total + (item.price * item.quantity);
        }, 0).toFixed(2);
    
        // 更新页面数据
        this.setData({
            selectedDishes: updatedSelectedDishes,
            filteredDishes: updatedFilteredDishes,
            dishes: updatedDishes,
            selectedItems,
            totalPrice: newTotal
        });
    
        // 更新本地存储
        this.updateCartStorage();
    },

    // 更新购物车本地存储和其他页面数据
    updateCartStorage() {
        const { selectedItems, totalPrice } = this.data;
    
        // 更新本地存储
        wx.setStorageSync('cartItems', selectedItems);
        wx.setStorageSync('selectedDishes', this.data.selectedDishes);
    
        // 更新购物车页面的数据
        const pages = getCurrentPages();
        const cartPage = pages.find(page => page.route === 'pages/cart/cart');
        if (cartPage) {
            cartPage.setData({
                cartItems: selectedItems,
                totalPrice
            });
        }
    },

    // 更新菜品数量显示
    updateDishesQuantity(selectedDishes) {
        const { dishes, filteredDishes } = this.data;
        
        // 更新所有菜品列表中的数量
        const updatedDishes = dishes.map(dish => ({
            ...dish,
            quantity: selectedDishes[dish.id] || 0
        }));

        // 更新筛选后的菜品列表中的数量
        const updatedFilteredDishes = filteredDishes.map(dish => ({
            ...dish,
            quantity: selectedDishes[dish.id] || 0
        }));

        // 更新页面数据
        this.setData({
            dishes: updatedDishes,
            filteredDishes: updatedFilteredDishes
        });
    },

    // 跳转到商品详情页
    navigateToDetail(e) {
        const id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/goods-detail/goods-detail?id=${id}`
        });
    },
})
